class Food extends egret.Sprite{

	private static pool:Array<Food> = [];
	static create():Food{
		let f:Food;
		if(Food.pool.length > 0){
			f = Food.pool.shift();
		}else{
			f = new Food();
		}
		return f;
	}
	
	unit:Unit;
	life:number;
	gx:number = 0;
	gy:number = 0;
	private twinkleSpeed:number = -0.1;
	constructor(){
		super();
		this.unit = Unit.create(0);
		this.addChild(this.unit);
		this.life = MAX_FOOD_LIFE;
	}

	setPos(gx:number,gy:number){
		this.gx = gx;
		this.gy = gy;
		this.x = gx * GRID_SIZE;
		this.y = gy * GRID_SIZE;
	}

	update():boolean{//is dead
		if(this.life <= 0){
			this.destroy();
			return true;
		}
		this.life --;
		if(this.life <= TWINKLE_FOOD_LIFE){
			this.twinkle(true);
		}
		return false;
	}

	destroy(){
		this.twinkle(false);
		this.alpha = 1;
		this.life = MAX_FOOD_LIFE;
		if(this.parent != null){
			this.parent.removeChild(this);
		}
		Food.pool.push(this);
	}

	twinkle(bool:boolean){
		this.removeEventListener(egret.Event.ENTER_FRAME,this.onEnterFrame,this);
		if(bool){
			this.addEventListener(egret.Event.ENTER_FRAME,this.onEnterFrame,this);
		}
	}

	private onEnterFrame(e:egret.Event){
		let add:boolean = this.twinkleSpeed == 0.1;
		this.alpha += this.twinkleSpeed;
		if(this.alpha >= 1 && add){
			this.twinkleSpeed = -0.1;
		}else if(this.alpha <= 0 && !add){
			this.twinkleSpeed = 0.1;
		}
	}

}
